<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="工序编码" prop="processCode">
        <el-input v-model="searchForm.processCode" placeholder="请输入工序编码" clearable />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input v-model="searchForm.processName" placeholder="请输入工序名称" clearable />
      </el-form-item>
      <el-form-item label="工序状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
          <el-option label="初始化" value="initialized" />
          <el-option label="已分配" value="assigned" />
          <el-option label="运行中" value="running" />
          <el-option label="已暂停" value="paused" />
          <el-option label="已完成" value="completed" />
          <el-option label="异常" value="error" />
          <el-option label="已取消" value="cancelled" />
          <el-option label="已停止" value="stopped" />
          <el-option label="已挂起" value="hold" />
          <el-option label="已报废" value="scrapped" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单ID" prop="workOrderId">
        <el-input v-model="searchForm.workOrderId" placeholder="请输入工单ID" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增工序</el-button>
      <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="processCode" label="工序编码" />
      <el-table-column prop="processName" label="工序名称" />
      <el-table-column prop="workOrderId" label="工单ID" />
      <el-table-column prop="status" label="工序状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" />
      <el-table-column label="操作" width="500" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="handleView(scope.row)" class="operation-btn">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)" class="operation-btn">编辑</el-button>

          <!-- 根据状态显示不同操作按钮 -->
          <el-button
            v-if="scope.row.status === 'initialized'"
            type="success"
            link
            @click="handleAssign(scope.row)"
            class="operation-btn"
            >分配</el-button
          >
          <el-button
            v-if="scope.row.status === 'assigned'"
            type="warning"
            link
            @click="handleStart(scope.row)"
            class="operation-btn"
            >开始</el-button
          >
          <el-button
            v-if="scope.row.status === 'running'"
            type="warning"
            link
            @click="handlePause(scope.row)"
            class="operation-btn"
            >暂停</el-button
          >
          <el-button
            v-if="scope.row.status === 'paused'"
            type="success"
            link
            @click="handleResume(scope.row)"
            class="operation-btn"
            >恢复</el-button
          >
          <el-button v-if="scope.row.status === 'running'" type="info" link @click="handleHold(scope.row)" class="operation-btn"
            >挂起</el-button
          >
          <el-button
            v-if="scope.row.status === 'hold'"
            type="success"
            link
            @click="handleRelease(scope.row)"
            class="operation-btn"
            >解挂</el-button
          >
          <el-button
            v-if="scope.row.status === 'running'"
            type="success"
            link
            @click="handleComplete(scope.row)"
            class="operation-btn"
            >完成</el-button
          >
          <el-button
            v-if="['running', 'paused'].includes(scope.row.status)"
            type="warning"
            link
            @click="handleRework(scope.row)"
            class="operation-btn"
            >返工</el-button
          >
          <el-button
            v-if="['initialized', 'completed', 'cancelled', 'scrapped'].includes(scope.row.status)"
            type="danger"
            link
            @click="handleDelete(scope.row)"
            class="operation-btn"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 工序表单抽屉 -->
    <ProcessForm ref="formDrawerRef" />
  </div>
</template>

<script setup lang="ts" name="processTable">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import ProcessForm from "./form.vue";
import { PageHelper } from "@/utils/pageHelper";
import {
  getProcessList,
  startProcess,
  pauseProcess,
  resumeProcess,
  completeProcess,
  assignProcess,
  holdProcess,
  releaseProcess,
  reworkProcess,
  deleteProcess,
  batchDeleteProcess,
  type Process
} from "@/api/modules/process";

const loading = ref(false);
const tableData = ref<Process.ProcessListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const selectedRows = ref<Process.ProcessListItem[]>([]);

// 查询表单
const searchForm = reactive({
  processCode: "",
  processName: "",
  status: "",
  workOrderId: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    initialized: "info",
    assigned: "warning",
    running: "primary",
    paused: "warning",
    completed: "success",
    error: "danger",
    cancelled: "info",
    stopped: "warning",
    hold: "danger",
    scrapped: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    initialized: "初始化",
    assigned: "已分配",
    running: "运行中",
    paused: "已暂停",
    completed: "已完成",
    error: "异常",
    cancelled: "已取消",
    stopped: "已停止",
    hold: "已挂起",
    scrapped: "已报废"
  };
  return statusMap[status] || status;
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = PageHelper.createPageParams(pagination.currentPage, pagination.pageSize, searchForm);
    const res = await getProcessList(params);

    // 使用PageHelper安全解析分页数据
    const pageData = PageHelper.parsePage<Process.ProcessListItem>(res.data);
    tableData.value = pageData.records;
    pagination.total = pageData.total;

    console.log("解析后的分页数据:", pageData);
  } catch (error) {
    console.error("获取工序列表失败:", error);
    ElMessage.error("获取工序列表失败");
  } finally {
    loading.value = false;
  }
};

// 表格选择项变化
const handleSelectionChange = (rows: Process.ProcessListItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;

  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const ids = selectedRows.value.map(row => row.id);
        await batchDeleteProcess(ids);
        ElMessage.success("批量删除成功");
        selectedRows.value = [];
        getTableData();
      } catch (error) {
        console.error("批量删除失败:", error);
        ElMessage.error("批量删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 工序表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof ProcessForm>>();

// 新增工序
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 查看工序
const handleView = (row: Process.ProcessListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 编辑工序
const handleEdit = (row: Process.ProcessListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    getTableList: getTableData
  };
  formDrawerRef.value?.open(params);
};

// 分配工序
const handleAssign = async (row: Process.ProcessListItem) => {
  try {
    const { value: formData } = await ElMessageBox.prompt("请输入分配信息（格式：工位ID,设备ID）", "分配工序", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^\d+,\d+$/,
      inputErrorMessage: "请输入正确格式：工位ID,设备ID"
    });

    const [workstationId, equipmentId] = formData.split(",");
    await assignProcess({
      processId: row.id,
      workstationId,
      equipmentId
    });
    ElMessage.success("工序分配成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("工序分配失败:", error);
      ElMessage.error("工序分配失败");
    }
  }
};

// 开始工序
const handleStart = async (row: Process.ProcessListItem) => {
  try {
    const { value: formData } = await ElMessageBox.prompt("请输入开始信息（格式：工单ID,设备ID,操作人ID）", "开始工序", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^.+,.+,.+$/,
      inputErrorMessage: "请输入正确格式：工单ID,设备ID,操作人ID"
    });

    const [workOrderId, equipmentId, operatorId] = formData.split(",");
    await startProcess({
      processId: row.id,
      workOrderId,
      equipmentId,
      operatorId
    });
    ElMessage.success("工序开始成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("工序开始失败:", error);
      ElMessage.error("工序开始失败");
    }
  }
};

// 暂停工序
const handlePause = async (row: Process.ProcessListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt("请输入暂停原因", "暂停工序", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /.+/,
      inputErrorMessage: "暂停原因不能为空"
    });

    await pauseProcess({
      processId: row.id,
      operatorId: "current_user", // 这里应该从用户上下文获取
      reason
    });
    ElMessage.success("工序暂停成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("工序暂停失败:", error);
      ElMessage.error("工序暂停失败");
    }
  }
};

// 恢复工序
const handleResume = async (row: Process.ProcessListItem) => {
  try {
    await resumeProcess({
      processId: row.id,
      operatorId: "current_user" // 这里应该从用户上下文获取
    });
    ElMessage.success("工序恢复成功");
    getTableData();
  } catch (error) {
    console.error("工序恢复失败:", error);
    ElMessage.error("工序恢复失败");
  }
};

// 挂起工序
const handleHold = async (row: Process.ProcessListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt("请输入挂起原因", "挂起工序", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /.+/,
      inputErrorMessage: "挂起原因不能为空"
    });

    await holdProcess({
      processId: row.id,
      operatorId: "current_user", // 这里应该从用户上下文获取
      reason
    });
    ElMessage.success("工序挂起成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("工序挂起失败:", error);
      ElMessage.error("工序挂起失败");
    }
  }
};

// 解除挂起
const handleRelease = async (row: Process.ProcessListItem) => {
  try {
    await releaseProcess({
      processId: row.id,
      operatorId: "current_user" // 这里应该从用户上下文获取
    });
    ElMessage.success("工序解挂成功");
    getTableData();
  } catch (error) {
    console.error("工序解挂失败:", error);
    ElMessage.error("工序解挂失败");
  }
};

// 完成工序
const handleComplete = async (row: Process.ProcessListItem) => {
  try {
    await completeProcess({
      processId: row.id,
      operatorId: "current_user" // 这里应该从用户上下文获取
    });
    ElMessage.success("工序完成成功");
    getTableData();
  } catch (error) {
    console.error("工序完成失败:", error);
    ElMessage.error("工序完成失败");
  }
};

// 工序返工
const handleRework = async (row: Process.ProcessListItem) => {
  try {
    const { value: reason } = await ElMessageBox.prompt("请输入返工原因", "工序返工", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /.+/,
      inputErrorMessage: "返工原因不能为空"
    });

    await reworkProcess({
      processId: row.id,
      operatorId: "current_user", // 这里应该从用户上下文获取
      reason
    });
    ElMessage.success("工序返工成功");
    getTableData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("工序返工失败:", error);
      ElMessage.error("工序返工失败");
    }
  }
};

// 删除工序
const handleDelete = async (row: Process.ProcessListItem) => {
  ElMessageBox.confirm(`确认删除工序 "${row.processCode}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteProcess(row.id);
        ElMessage.success("工序删除成功");
        getTableData();
      } catch (error) {
        console.error("工序删除失败:", error);
        ElMessage.error("工序删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 14px;
  margin: 0 2px;
}

:deep(.operation-btn .el-icon) {
  font-size: 16px;
  margin-right: 2px;
}
</style>